<template>
    <el-container>
        <el-header v-if="realOptions.toolbar.enable" style="height: auto" class="py-10 not-valid">
            <slot name="toolbar" v-bind:loadData="loadData"></slot>
        </el-header>
        <el-main :class="{ 'hjk-table-data': hjkTableData }">
            <el-table  class="dataTable" :class="{ 'hjk-table-spacing': spacing }" ref="dataTable"
                       @row-click="rowExpand" @row-dblclick="rowDblclick" :height="reHeight" :data="dataList"
                       :empty-text="emptyText" :row-style="rowStyle" :row-class-name="tableRowClassName"
                       v-bind="realOptions.table" @select-all="handleSelectionChange" @select="select"
                       :highlight-current-row="higHlight" @expand-change="handleExpandChange"
                       style="border-bottom: #dcdee2 solid 1px" border>
                <template v-for="(column, index) in columnList">
                    <el-table-column v-if="column.type == 'index'" v-bind="column">
                        <template slot-scope="current">{{ indexNo(current.$index) }}</template>
                    </el-table-column>
                    <el-table-column v-else-if="column.slotName !== void 0" v-bind="column">
                        <template slot-scope="current">
                            <slot :name="column.slotName" v-bind:prop="column.prop" v-bind:index="current.$index"
                                  v-bind:row="current.row" v-bind:current="current" v-bind:refresh="refresh"></slot>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column v-else-if="column.dictionary" v-bind="column">
                        <template slot-scope="current">{{ current.row[column.prop] === void 0 && column.emptyFormat !==
            void 0 ? column.emptyFormat : current.row[column.prop] | dictionary(column.dictionary)
                            }}</template>
                    </el-table-column> -->
                    <el-table-column v-else-if="column.filter != void 0" v-bind="column">
                        <template slot-scope="current">{{ column.filter(current.row[column.prop], current.row)
                            }}</template>
                    </el-table-column>
                    <el-table-column v-else-if="column.type == 'selection'" v-bind="column"></el-table-column>
                    <el-table-column v-else-if="column.emptyFormat !== void 0" v-bind="column">
                        <template slot-scope="current">{{ current.row[column.prop] === void 0 && column.emptyFormat !==
                            void 0 ? column.emptyFormat : current.row[column.prop] }}</template>
                    </el-table-column>
                    <el-table-column v-else v-bind="column"></el-table-column>
                </template>
            </el-table>
        </el-main>
        <el-footer class="table-data-pagination" v-if="realOptions.pagination.enable">
            <div>
                <slot name="operator"></slot>
            </div>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
                           v-bind="realOptions.pagination"></el-pagination>
        </el-footer>
    </el-container>
</template>

<script>
    export default {
        name: "HjkDataTable",
        loading: true,
        props: {
            emptyText: {
                default: "暂无数据"
            },
            reduceHeight: {
                type: Number,
                default() {
                    return 0;
                }
            },
            data: {
                type: [Array],
                default() {
                    return [];
                }
            },
            options: {
                type: [Object],
                default() {
                    return {};
                }
            },
            columns: {
                type: [Array],
                default() {
                    return [];
                }
            },
            url: String,
            hjkService: Object,
            hjkServiceType: {
                default: "post"
            },
            timeOut: {
                type: Number,
                default() {
                    return 10000;
                }
            },
            isEnable: {
                default: true
            },
            higHlight: {
                default: false
            },
            rowClassName: {
                default: ""
            },
            hjkTableData: {
                default: false
            },
            height: {
                default: ""
            },
            spacing: {
                default: true
            },
            isSizes: {
                default: false
            },
            currentPage: {
                default: 1
            }
        },
        data() {
            return {
                isShow: true,
                defaultOptions: {
                    toolbar: {
                        enable: true
                    },
                    pagination: {
                        enable: this.isEnable,
                        "page-sizes": [10, 15, 20, 50, 100, 500],
                        "page-size": 10,
                        layout: "total, sizes, prev, pager, next, jumper",
                        total: 0,
                        "current-page": 1
                    },
                    table: {
                        border: false
                    },
                    condition() {
                        return {};
                    },
                    method: "post",
                    order: [],
                    params: {}
                },
                realOptions: { pagination: { "page-size": 10, "current-page": 1 } },
                dataList: [],
                capacity: 10,
                first: 0,
                selectedRow: [],
                tableHeight: window.innerHeight - 267
            };
        },
        computed: {
            columnList() {
                let list = this.columns
                    .filter(x => x)
                    .map(x => {
                        return {
                            "show-overflow-tooltip": x.slotName != "opt",
                            ...x
                        };
                    });
                return list;
            },
            reHeight() {
                if (this.height == "auto") {
                    return undefined;
                }
                return (this.height || this.tableHeight) - this.reduceHeight;
            }
        },
        created() {
            let that = this;
            window.onresize = function () {
                that.tableHeight = window.innerHeight - 267;
            };
            if (document.createEvent) {
                var event = document.createEvent("HTMLEvents");
                event.initEvent("resize", true, true);
                window.dispatchEvent(event);
            } else if (document.createEventObject) {
                window.fireEvent("onresize");
            }
            this.loadDefaultOptions();
            if (this.options.url || this.hjkService) {
                if (this.options.firstLoad == void 0 || this.options.firstLoad) {
                    if (this.currentPage == 1) {
                        this.loadData(1);
                    } else {
                        this.loadData(this.currentPage);
                    }
                }
            }
        },
        methods: {
            tableRowClassName({ row }) {
                return this.rowClassName ? this.rowClassName(row) : "";
            },
            indexNo(index) {
                let number = this.realOptions.pagination["current-page"];
                let capacity = this.realOptions.pagination["page-size"];
                return index + 1 + number * capacity - capacity;
            },
            selectChange(data) {
                this.selectedRow = [];
                if (data.length > 0) {
                    data.forEach(x => {
                        this.selectedRow.push(this.dataList.indexOf(x));
                    });
                }
            },
            select(val, row) {
                this.selectChange(val);
                this.$emit("select", { val, row });
            },
            handleSelectionChange(val) {
                this.selectChange(val);
                this.$emit("selection-all", val);
            },
            rowStyle({ row, rowIndex }) {
                if (this.selectedRow.includes(rowIndex)) {
                    return { "background-color": "#ecf5ff" };
                }
                return {};
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.dataTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.dataTable.clearSelection();
                }
            },
            loadDefaultOptions() {
                this.realOptions = _.merge({}, this.defaultOptions, this.options);
                this.capacity = this.realOptions.pagination["page-size"];
            },
            handleSizeChange(pageSize) {
                this.capacity = pageSize;
                let current = Math.ceil((this.first + 1) / pageSize);
                this.realOptions.pagination["page-size"] = pageSize;
                this.realOptions.pagination["current-page"] = current;
                this.loadData(current, dataList => {
                    this.$emit("change", dataList);
                });
            },
            handleCurrentChange(currentPage) {
                this.loadData(currentPage, dataList => {
                    this.$emit("change", dataList);
                });
            },
            async buildCondition(number) {
                let control = { warp: true };
                let condition = {};
                if (this.realOptions.type == "async") {
                    condition = await this.realOptions.condition(control);
                } else {
                    condition = this.realOptions.condition(control);
                }
                let data = {};
                if (control.warp) {
                    if (this.realOptions.method == "postJson" || this.hjkService) {
                        data.conditions = {
                            ...condition
                        };
                    } else {
                        _.map(condition, (v, k) => {
                            data[`conditions['${k}']`] = v;
                        });
                    }
                } else {
                    data = condition;
                }
                let option = _.merge({}, this.realOptions.params, { capacity: this.capacity, number: number }, data);
                if (window.screen.height >= 768 && option.capacity < 20) {
                    option.capacity = 100;
                    this.realOptions.pagination["page-sizes"] = [100, 500, 1000];
                    this.realOptions.pagination["page-size"] = option.capacity;
                }
                if (this.isSizes) {
                    this.realOptions.pagination.layout = "sizes,total, prev, pager, next";
                }
                console.log(option);
                if (this.realOptions.method == "postJson" && !Object.values(option.conditions).filter(x=>x).length) {
                    delete option.conditions
                }
                return option;
            },
            async loadData(page, callback, isShow) {
                this.realOptions.pagination.enable = false;
                this.selectedRow = [];
                page = page === void 0 ? 1 : page;
                this.realOptions.pagination["current-page"] = page;
                let data = await this.buildCondition(page);
                this.realOptions.pagination.enable = true;
                let dataCall = res => {
                    console.log(res)
                    if (res) {
                        let pageData = void 0;
                        //res:{page:Page}
                        if (res.data && res.data.pageInfo) {
                            pageData = res.data.pageInfo;
                            //SSTO:{data:Page}
                        } else if (res.data && res.data.pageInfo) {
                            pageData = res.data.pageInfo;
                        }
                        if (pageData) {
                            this.dataList = pageData.list;
                            this.realOptions.pagination.total = pageData.total;
                            pageData.first && (this.first = pageData.first);
                            if (callback) {
                                callback(this.dataList);
                            }
                            this.$emit("loaded", this.dataList);
                        }
                    }
                };
                let options = {
                    url: this.options.url,
                    data: data,
                    isLoadingShow: this.realOptions.isLoadingShow,
                    timeout: this.timeOut
                };
                console.log(options);

                // window.$rootVue.$http.params({url:options.url, data:options.data}).then(dataCall)

                this.$http[this.realOptions.method](options).then(dataCall);
            },
            refresh() {
                this.loadData(this.realOptions.pagination["current-page"]);
            },
            selectedRows() {
                return this.$refs.dataTable.selection;
            },
            rowExpand(row) {
                if (this.columns.filter(x => x && x.type && x.type == "expand").length > 0) {
                    this.$refs.dataTable.toggleRowExpansion(row);
                }
                this.$emit("row-click", row);
            },
            rowDblclick(row) {
                this.$emit("row-dblclick", row);
            },
            handleExpandChange(row, expandedRows) {
                this.$emit("expand-change", row, expandedRows);
            }
        },
        watch: {
            columns: {
                handler() {
                    this.isShow = !this.isShow;
                    setTimeout(() => {
                        this.isShow = !this.isShow;
                    }, 50);
                },
                deep: true
            },
            options: {
                handler() {
                    this.loadDefaultOptions();
                },
                deep: true
            },
            data: {
                immediate: true,
                handler(val) {
                    this.dataList = val;
                },
                deep: true
            }
        }
    };
</script>

<style>
    .el-main{
        padding:20px 0px !important
    }

    .table-data-pagination{
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-table {
        font-size: 5px;
    }

</style>
